<template>
  <view class="container">
    <!-- 固定在顶部的搜索栏和分段控制器 -->
    <view class="fixed-header">
      <u-search 
        placeholder="请输入设备名称" 
        shape="round" 
        :showAction="false" 
        @change="toSearch" 
        v-model="keyword"
        height="70rpx"
      ></u-search>
      <u-subsection 
        :list="sublist" 
        style="margin-top:15rpx;"
        :current="currentIndex" 
        @change="changeIndex"
        active-color="#4a90e2"
      ></u-subsection>
    </view>
    
    <!-- 可滚动内容区域 -->
    <scroll-view 
      scroll-y="true" 
      @scrolltolower="handleReachBottom" 
      @scroll="onScroll"
      :scroll-top="scrollTopValue"
      :enhanced="true"  
      :show-scrollbar="false"
      style="height: calc(100vh - 10rpx);"  
    >
      <!-- 内容容器 -->
      <view class="scroll-content">
        <view class="mainContent">
          <!-- 加载状态 -->
          <view class="loading" v-if="loading && current > 1">
            <u-loading-icon size="28" color="#4a90e2"></u-loading-icon>
            <text class="loading-text">加载中...</text>
          </view>

          <view class="deviceList" v-if="tableData.length">
            <view 
              class="device" 
              :class="{ 'device-online': item.online }"
              v-for="(item, index) in tableData" 
              :key="index"
            >
              <view class="deviceContent">
                <view class="leftImg">
                  <image src="@/static/device.png" alt="设备图标" mode="widthFix" />
                </view>
                <view class="deviceInfo">
                  <p>设备编号:{{ item.id }}</p>
                  <p>设备名称:{{ item.deviceName }}</p>
                  <p>项目名称:{{ item.projectName }}</p>
                </view>
              </view>
              <view class="operation">
                <p @click.stop="toDetails(item.id)">详情</p>
              </view>
              <view class="stateView" :class="item.online ? 'state-online' : 'state-offline'">
                {{ item.online ? '在线' : '休眠' }}
              </view>
            </view>
          </view>

          <view class="empty-container" v-else-if="!loading">
            <image class="empty-image"
              src="https://img0.baidu.com/it/u=3104160226,4142277399&fm=253&fmt=auto&app=138&f=JPEG?w=499&h=408"
              mode="aspectFit" />
            <view class="empty-text">{{ emptyText || '暂无数据' }}</view>
            <view class="empty-button" @click="toSearch">
              刷新
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    
   
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { ddevicePageApi } from "@/axios/pageApi/device";
import { onReady } from "@dcloudio/uni-app";

// 状态管理
let scrollTopValue = ref(0);
let scrollTimer = null;
let isScrolling = ref(false);
let isLoadingMore = ref(false); // 防止重复加载

// 数据状态
let sublist = ref(['全部', '在线', '休眠']);
let keyword = ref('');
let current = ref(1);
let loading = ref(false);
let currentIndex = ref(0);
let tableData = ref([]);
let hasMore = ref(true); // 控制是否还有更多数据

// 初始化
onReady(() => {
  getdeviceData();
});

// 搜索设备
function toSearch() {
  current.value = 1;
  tableData.value = [];
  hasMore.value = true;
  getdeviceData();
  backToTop();
}

// 滚动事件处理（仅用于更新滚动位置，不控制按钮显示）
// function onScroll(e) {
//   // 避免频繁更新导致的抖动
//   if (scrollTimer) clearTimeout(scrollTimer);
  
//   scrollTimer = setTimeout(() => {
//     scrollTopValue.value = e.detail.scrollTop;
//     isScrolling.value = false;
//   }, 16); // 与屏幕刷新率同步
  
//   isScrolling.value = true;
// }

// 平滑滚动到顶部
function backToTop() {
  
  const start = scrollTopValue.value;
  const duration = 300;
  const interval = 16;
  const totalSteps = duration / interval;
  let currentStep = 0;
  
  const timer = setInterval(() => {
    currentStep++;
    if (currentStep >= totalSteps) {
      scrollTopValue.value = 0;
      clearInterval(timer);
      return;
    }
    
    // 缓动函数优化滚动体验
    const progress = 1 - Math.pow(1 - currentStep / totalSteps, 3);
    scrollTopValue.value = start - (start * progress);
  }, interval);
}

// 获取设备数据
async function getdeviceData() {
  if (loading.value && current.value > 1) return;
  
  loading.value = true;
  try {
    const onlineStatus = currentIndex.value == 0 
      ? '' 
      : currentIndex.value == 2 ? 0 : 1;
      
    const res = await ddevicePageApi({
      deviceName: keyword.value,
      current: current.value,
      online: onlineStatus
    });
    
    if (res.code == 0) {
      const newData = res.data.records || [];
      if (current.value == 1) {
        tableData.value = newData;
      } else {
        tableData.value = [...tableData.value, ...newData];
      }
      
      // 控制是否还有更多数据
      hasMore.value = tableData.value.length < res.data.total;
    }
  } catch (error) {
    console.error('获取设备数据失败:', error);
  } finally {
    loading.value = false;
    isLoadingMore.value = false;
  }
}

// 加载更多
function handleReachBottom() {
  if (isLoadingMore.value || !hasMore.value) return;
  
  isLoadingMore.value = true;
  current.value++;
  getdeviceData();
}

// 切换在线状态
function changeIndex(e) {
  currentIndex.value = e;
  toSearch();
}

// 跳转详情
function toDetails(item) {
  uni.navigateTo({
    url: `/pages/detailsPage/detailsPage?name=${item}`
  });
}

// 清理定时器
onUnmounted(() => {
  if (scrollTimer) clearTimeout(scrollTimer);
});
</script>

<style scoped lang="scss">
.container {
  height: 100vh;
  position: relative;
  background-color: #f5f7fa;
  overflow: hidden;
}

/* 固定头部 */
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 99;
  padding: 16rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transform: translateZ(0); /* 硬件加速 */
}

/* 滚动内容容器 */
.scroll-content {
  padding-top: 170rpx; /* 避开固定头部 */
}

.mainContent {
  padding: 10rpx;
}

/* 设备列表样式 */
.deviceList {
  display: flex;
  flex-direction: column;
  gap: 20rpx; /* 使用gap替代margin减少重排 */
  padding: 10rpx;
}

.device {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  font-size: 24rpx;
  border-radius: 12rpx;
  background-color: #fff;
  position: relative;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  will-change: transform; /* 优化滚动性能 */
}

.device-online {
  border: 1px solid #4a90e2;
}

.deviceContent {
  display: flex;
  align-items: center;
}

.leftImg {
  width: 80px;
  height: 80px;
  border-radius: 8rpx;
  overflow: hidden;
  flex-shrink: 0; /* 防止被压缩 */
}

.leftImg image {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 图片自适应 */
}

.deviceInfo {
  margin-left: 20rpx;
  flex: 1;
  min-width: 0; /* 解决文本溢出问题 */
}

.deviceInfo p {
  margin-bottom: 10rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis; /* 文本溢出显示省略号 */
}

.operation {
  text-align: center;
  margin-right: 30rpx;
  font-size: 26rpx;
  color: #4a90e2;
  flex-shrink: 0;
}

.stateView {
  position: absolute;
  right: 20rpx;
  top: -12rpx;
  border-radius: 20rpx;
  padding: 4rpx 16rpx;
  font-size: 22rpx;
  font-weight: 500;
}

.state-online {
  background-color: #4a90e2;
  color: #fff;
}

.state-offline {
  background-color: #ccc;
  color: #fff;
}

/* 加载状态 */
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx 0;
  color: #666;
  font-size: 26rpx;
}

.loading-text {
  margin-left: 10rpx;
}

/* 空状态样式 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
  opacity: 0.7;
}

.empty-text {
  font-size: 28rpx;
  margin-bottom: 40rpx;
}

.empty-button {
  color: #4a90e2;
  border: 1px solid #4a90e2;
  border-radius: 8rpx;
  padding: 16rpx 40rpx;
  font-size: 28rpx;
  transition: all 0.2s;
}

.empty-button:active {
  background-color: #f0f7ff;
}

/* 固定显示的返回顶部按钮 */
.back-to-top {
  position: fixed;
  bottom: 50rpx;
  right: 30rpx;
  width: 80rpx;
  height: 80rpx;
  background-color: rgba(74, 144, 226, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  z-index: 99;
  opacity: 0.9;
  transition: all 0.2s;
}

.back-to-top:active {
  transform: scale(0.95);
  background-color: #3a80d2;
}

/* 适配不同屏幕 */
@media (max-width: 375px) {
  .deviceInfo {
    font-size: 22rpx;
  }
  
  .leftImg {
    width: 70px;
    height: 70px;
  }
}
</style>
